package com.cssw.fyzb.busi.config;

import com.ydn.appserver.ClientConfiguration;
import com.ydn.appserver.MinaAppClient;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.Map;

/**
 * @author YangYiQun
 */
@Component
public class EventClient {

    @Value("${event.addrs}")
    private String addrs;

    @Value("${event.maxConn:64}")
    private int maxConn;

    @Value("${event.coTimeout:3000}")
    private int coTimeout;

    @Value("${event.soTimeout:3000}")
    private int soTimeout;

    private MinaAppClient delegate;

    @PostConstruct
    public void start() {
        ClientConfiguration configuration = new ClientConfiguration();
        configuration.setServerAddressesString(addrs);
        configuration.setMaxConnectionsPerServer(maxConn);
        configuration.setSocketConnTimeoutSec(coTimeout);
        configuration.setSocketDataTimeoutSec(soTimeout);
        delegate = new MinaAppClient(configuration);
    }

    @PreDestroy
    public void close() {
        if (delegate != null) {
            delegate.close();
        }
    }

    /**
     * 经纬度转地址
     *
     * @param topic 主题
     * @param message 消息
     * @return
     */
    public void fireEvent(String topic, String message) {
        Map<String, Object> param = new HashMap<>();
        param.put("topic", topic);
        param.put("message", message);
        get("FireEvent", param);
    }

    private boolean get(String action, Map<String, Object> params) {
        Request request = new Request(action);
        for (Map.Entry<String, Object> param : params.entrySet()) {
            Object value = param.getValue();
            if (value != null) {
                request.setParameter(param.getKey(), String.valueOf(value));
            }
        }
        Response response = delegate.send(request);
        return response.isSuccess();
    }

    public Response send(Request request){
        return delegate.send(request);
    }

}
